package com.bw.task.activity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bw.library.mvp.view.BaseActivity;
import com.bw.task.R;
import com.bw.task.bean.ImgBean;
import com.bw.task.bean.MoneyBean;
import com.bw.task.bean.PopupWindioBean;
import com.bw.task.bean.UserBean;
import com.bw.task.bean.ZFBean;
import com.bw.task.db.DaoMaster;
import com.bw.task.db.DaoSession;
import com.bw.task.db.User;
import com.bw.task.db.UserDao;
import com.bw.task.mvp.contern.UserContent;
import com.bw.task.mvp.model.UserModel;
import com.bw.task.mvp.persenter.UserPersenter;
import com.bw.task.zfb.PayResult;
import com.bw.task.zfb.util.OrderInfoUtil2_0;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Map;

public class PayActivity extends BaseActivity<UserPersenter> implements UserContent.mView {

    private EditText moneytext;
    SharedPreferences.Editor edit;
    String nameby;
    UserDao userDao;
    private android.widget.Button notifation;


    @Override
    public int bandLayout() {
        return R.layout.activity_pay;
    }

    @Override
    public void initData() {


        notifation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNotification();
            }
        });


        DaoMaster.DevOpenHelper usera = new DaoMaster.DevOpenHelper(this, "usera");
        SQLiteDatabase writableDatabase = usera.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        DaoSession daoSession = daoMaster.newSession();

        userDao = daoSession.getUserDao();


        mPresenter=new UserPersenter(this,new UserModel());
        EventBus.getDefault().register(this);

        SharedPreferences user = getSharedPreferences("user", MODE_PRIVATE);

        edit = user.edit();

        nameby = user.getString("userid", "");
    }

    public void initView() {
        moneytext = (EditText) findViewById(R.id.moneytext);
        notifation = (Button) findViewById(R.id.notifation);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(sticky = true)
    public void event(String k){

    }
    //20元
    public void twenty(View view) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        payV2(20);
    }

    //50元
    public void fifty(View view) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        payV2(50);
    }

    //80元
    public void eighty(View view) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        payV2(80);
    }

    //自定义
    public void money(View view) {
        String trim = moneytext.getText().toString().trim();
        Integer integer = Integer.valueOf(trim);
        Toast.makeText(this, "充值"+integer+"元", Toast.LENGTH_SHORT).show();
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        payV2(integer);
    }




    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2021000117666906";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwgg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5Ujn/JowsbTQHmrJoF6EfUWuA1ONZU4Xs4yYKR8ho+C9dhSIUPnpCnZb/MQ1myloy70vJ2JtV/X4oUwaJ6eBJwAtqKDJ/qwFm7o8pQCf9zzCtv9r/To8Aon9Ml9Fa9xZjTrI1xuvdFSn1tDQXMow49cD3ry4XXfwM98D5wKBgD22ir/CET12l+ya0GO1FCpI0Fgc8scWS1ht1b2p4aE3KnJYmBBmbDuHaGj989kGzmMeOnQyJaQhVmLociPfkVkoFPz6wXLPCrYRbp2u4HGE73w39fnSbtI1fCwBono5YEekgIr2wj9iHiUzOoWDRTCITD6O7VDbp68SMHTCmRAtAoGBAN71/mXkmubvG5hjd74SSa3n0tzFJvWwCq0X8lkLnDqL+c5BW87q2dCJcXuSk5OJwTOE6n0KILbq/vHtaKfkV4QBdOzS8AQCDIY26zxauR4+fAhtMeBXjc4bjoHv6/6WRuCUZysBxYbOe7LEkEr1jmsN6SrYAGBRZlyPcAd31ccf";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        ToastUtils.showShort("支付成功");
                        moneytext.setText("");
                        Gson gson = new Gson();
                        ZFBean zfBean = gson.fromJson(resultInfo, ZFBean.class);
                        String moneyzf = zfBean.getAlipay_trade_app_pay_response().getTotal_amount();
                        getNotification();
                        mPresenter.getmonry(nameby,moneyzf);


                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付失败");
                        LogUtils.i("支付失败"+payResult.toString());

                    }
                    break;
                }

            }
        };
    };

    /**
     *  通知
     */
    @SuppressLint("RemoteViewLayout")
    public void getNotification(){

/*        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher_background);
        builder.setContentTitle("标题");
        builder.setContentText("内容。。。。。。");
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.act_notifion);
        remoteViews.setImageViewResource(R.id.notifation_img,R.drawable.ic_launcher_background);
        remoteViews.setTextViewText(R.id.notifion_text,"66666");
        builder.setContent(remoteViews);
        manager.notify(2,builder.build());
        */


        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder1 = new Notification.Builder(this);
        builder1.setSmallIcon(R.drawable.ic_launcher_background);
        builder1.setContentTitle("标题");
        builder1.setContentText("213456798");
        notificationManager.notify(2,builder1.build());



    }


    /**
     * 支付宝支付业务示例
     */
    public void payV2(int money) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2,money);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void UserBean(UserBean userBean) {

    }

    @Override
    public void LogUserBean(UserBean userBean) {

    }

    @Override
    public void MoneyUserBean(MoneyBean userBean) {
        String money = userBean.getData().getMoney()+"";
        String userName = userBean.getData().getUserName();
        String userPwd = userBean.getData().getUserPwd();
        Integer userId = userBean.getData().getUserId();
        List<User> users = userDao.queryRaw("where userid=?", nameby);
        Long id = users.get(0).getId();

        float v = Float.parseFloat(money);
        LogUtils.i(money);
        //修改
        User user = new User();
        user.setId(id);
        user.setName(userName);
        user.setPass(userPwd);
        user.setUserid(userId);
        user.setMoney(v);
        userDao.update(user);
        //查询
        List<User> users2 = userDao.queryRaw("where userid=?", nameby);
        LogUtils.i("支付数据库查询----"+"ID:"+users2.get(0).getId()+"--name:"+users2.get(0).getName()+"--pass:"+users2.get(0).getPass()+"--mID:"+users2.get(0).getUserid()+"--money:"+users2.get(0).getMoney());
        EventBus.getDefault().postSticky("ZFB:"+money);

    }

    @Override
    public void getImgBean(ImgBean imgBean) {

    }


}